# -------------------------------------------------------------------
# Purpose: Creates Table B09
# Author:  Max Posch, 25/07/2025
# Usage:   Source this script to generate the table.
# -------------------------------------------------------------------
# Check that required paths exist
stopifnot(dir.exists(pdataconfanalysis))
stopifnot(dir.exists(poutputappendix))


# Load data
load(file.path(pdataconfanalysis, "inventorLevel19001940.RData"))
d <- inventorLevel19001940[data.table::between(year, 1900, 1930)][!is.na(sum_immigrant_ws)]


## Winsorize and normalize ------------------------------------------------
fe_cols <- str_subset(names(d), "_w$")
d <- d[, (fe_cols) := NULL]

fe_cols <- str_subset(names(d), "_ws$")
d <- d[, (fe_cols) := NULL]

vars <- str_subset(names(d), "^sum[:graph:]+_f$")
d[, paste0(vars, "_w") := lapply(.SD, function(x) winsorize(x, probs = c(.1, .9))), .SDcols = vars]

vars <- str_subset(names(d), "entropy|sum_n_namelast_mp_adjp|immigrant")
d[, paste0(vars, "_w") := lapply(.SD, function(x) winsorize(x, probs = c(.01, .99))), .SDcols = vars]

vars <- str_subset(names(d), "entropy|sum_n_namelast_mp_adjp|immigrant")
vars <- str_subset(vars, "_w$")
d[, paste0(vars, "s") := lapply(.SD, scale), .SDcols = vars]


# Regressions
o <- list()
o <- append(o, list(feols(sum_patents_f_w ~ entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws | inv_id + year^statefip, d)))
o <- append(o, list(feols(sum_patents_f_w ~ entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws + sum_immigrant_ws | inv_id + year^statefip, d)))
o <- append(o, list(feols(sum_break_p80_rrfsim05_f_w ~ entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws | inv_id + year^statefip, d)))
o <- append(o, list(feols(sum_break_p80_rrfsim05_f_w ~ entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws + sum_immigrant_ws | inv_id + year^statefip, d)))

r <- list()
r <- append(r, list(feols(sum_patents_f_w ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws | inv_id + year^statefip, d)))
r <- append(r, list(feols(sum_patents_f_w ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws + sum_immigrant_ws | inv_id + year^statefip, d)))
r <- append(r, list(feols(sum_break_p80_rrfsim05_f_w ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws | inv_id + year^statefip, d)))
r <- append(r, list(feols(sum_break_p80_rrfsim05_f_w ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws + sum_immigrant_ws | inv_id + year^statefip, d)))

i <- list()
i <- append(i, list(feols(sum_patents_f_w ~ 1 | inv_id + year^statefip | entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws, d)))
i <- append(i, list(feols(sum_patents_f_w ~ sum_immigrant_ws | inv_id + year^statefip | entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws, d)))
i <- append(i, list(feols(sum_break_p80_rrfsim05_f_w ~ 1 | inv_id + year^statefip | entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws, d)))
i <- append(i, list(feols(sum_break_p80_rrfsim05_f_w ~ sum_immigrant_ws | inv_id + year^statefip | entropy_namelast_mp_adjp_ws + sum_n_namelast_mp_adjp_ws ~ iv_lo_entropy_namelast_mp_adjp_fe_immig_ws + iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws, d)))



# F-statistics
dstata <- inventorLevel19001940[, .(
  x1 = entropy_namelast_mp_adjp_ws, 
  z1 = iv_lo_entropy_namelast_mp_adjp_fe_immig_ws,
  x3 = sum_n_namelast_mp_adjp_ws, 
  z3 = iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws,
  x2 = sum_immigrant_ws,
  y1 = sum_patents_f_w, 
  y2 = sum_break_p80_rrfsim05_f_w,
  inv_id_f, gisjoin_1900_f, statefip_f, year_f
)]
commands <- list(
  'ivreghdfe y1 (x1 x3= z1 z3), absorb(inv_id_f year_f#statefip_f) cluster(statefip_f) first ffirst savefirst
   gen swf1 = .
   gen swf2 = .
   replace swf1 = round(e(first)["SWF",1])
   replace swf2 = round(e(first)["SWF",2])
   keep swf*
   keep if _n == 1',
    'ivreghdfe y1 x2 (x1 x3= z1 z3), absorb(inv_id_f year_f#statefip_f) cluster(statefip_f) first ffirst savefirst
   gen swf1 = .
   gen swf2 = .
   replace swf1 = round(e(first)["SWF",1])
   replace swf2 = round(e(first)["SWF",2])
   keep swf*
   keep if _n == 1'
)
swf_results <- as.character(unlist(lapply(commands, get_fstat_from_stata, data.in = dstata)))
swfstat <- rep(swf_results, times = 2)


# Create table
y1_mean <- round(mean(d$sum_patents_f_w), 2)
y1_sd <- round(sd(d$sum_patents_f_w), 2)
y2_mean <- round(mean(d$sum_break_p80_rrfsim05_f_w), 2)
y2_sd <- round(sd(d$sum_break_p80_rrfsim05_f_w), 2)
y1 <- paste0("\\makecell{Patents \\\\ (mean = ", y1_mean, ", sd = ", y1_sd, ")}")
y2 <- paste0("\\makecell{Breakthrough patents \\\\ (mean = ", y2_mean, ", sd = ", y2_sd, ")}")

setFixest_dict(
  c(
    entropy_namelast_mp_adjp_ws = "Surname diversity",
    iv_lo_entropy_namelast_mp_adjp_fe_immig_ws = "Predicted surname diversity",
    sum_n_namelast_mp_adjp_ws = "Population",
    iv_lo_sum_n_namelast_mp_adjp_fe_immig_tr_ws = "Predicted population",
    sum_immigrant_ws = "Immigration",
    sum_patents_f_w = y1, sum_break_p80_rrfsim05_f_w = y2,
    year = "Period", statefip = "State", gisjoin_1900 = "County", inv_id = "Inventor"
  )
)

tablename <- file.path(poutputappendix, "tableB09.tex")
etable(o,
  cluster = ~statefip,
  fitstat = ~n,
  order = c("diversity", "Immigration", "opulation"),
  digits = "r3", digits.stats = "r3",
  file = tablename, replace = TRUE,
  style.tex = style.tex("aer"), tex = TRUE
)
add_table_row(tablename, "\\midrule", "\\multicolumn{2}{l}{\\textit{Panel A: Least-squares estimates}} &  \\multicolumn{3}{c}{}\\\\ \\cmidrule(lr){1-5}")
add_table_row(tablename, "mean =", "\\cmidrule(lr){2-3}  \\cmidrule(lr){4-5}")
move_table_row(tablename, "Observations", "bottomrule")
add_table_row(tablename, "    \\\\", c("\\multicolumn{2}{l}{\\textit{Panel B: Reduced-form estimates}} &  \\multicolumn{3}{c}{}\\\\", "\\\\", "\\multicolumn{2}{l}{\\textit{Panel C: Instrumental-variable estimates}} &  \\multicolumn{3}{c}{}\\\\", "\\\\", "\\multicolumn{2}{l}{\\textit{Panel D: First-stage estimates}} &  \\multicolumn{3}{c}{}\\\\"))

temptable <- file.path(poutputappendix, "temp.tex")
etable(r,
  cluster = ~statefip,
  fitstat = ~n,
  order = c("diversity", "Immigration", "opulation"),
  digits = "r3", digits.stats = "r3",
  file = temptable, replace = TRUE,
  style.tex = style.tex("aer"), tex = TRUE
)
estimates_rows <- get_estimates_rows(temptable)
add_table_row(tablename, "Panel B", c("\\cmidrule(lr){1-5}", estimates_rows))

temptable <- file.path(poutputappendix, "temp.tex")
etable(i,
  cluster = ~statefip,
  fitstat = ~n,
  order = c("diversity", "Immigration", "opulation"),
  digits = "r3", digits.stats = "r3",
  extralines = list("Sanderson-Windmeijer \\textit{F}-stat" = swfstat),
  file = temptable, replace = TRUE,
  style.tex = style.tex("aer"), tex = TRUE
)
estimates_rows <- get_estimates_rows(temptable)
add_table_row(tablename, "Panel C", c("\\cmidrule(lr){1-5}", estimates_rows))
add_table_row(tablename, "Sanderson", "\\\\", "before")

temptable <- file.path(poutputappendix, "temp.tex")
etable(i,
  stage = 1,
  cluster = ~statefip,
  order = c("diversity", "Immigration", "opulation"),
  fitstat = ~n, digits = "r3", digits.stats = "r3",
  file = temptable, replace = TRUE,
  style.tex = style.tex("aer"), tex = TRUE
)
estimates_rows <- get_estimates_rows(temptable)
estimates_rows <- collapse_stage1(estimates_rows, c(2, 4, 3, 5))
add_table_row(tablename, "Panel D", estimates_rows)
add_table_row(tablename, "Panel D", c("\\cmidrule(lr){1-5}", "& \\multicolumn{2}{c}{Surname diversity} & \\multicolumn{2}{c}{Population}\\\\", "\\cmidrule(lr){2-3}  \\cmidrule(lr){4-5}"))
file.remove(temptable)

cat("Table B09 saved to:", tablename, "\n")